from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Thesis
from .serializers import ThesisDto, ThesisModelSerializer,ThesisPageQuery
import logging
from django.http import JsonResponse
from .models import Thesis

logger = logging.getLogger(__name__)

class ThesisView(APIView):
    def get(self, request, id):
        try:
            id = int(id)  # 确保 id 为整数类型
            logger.info(f"Received id: {id}")
            theses = Thesis.objects.filter(user_id=id)
            logger.info(f"Number of theses found: {theses.count()}")

            if not theses.exists():
                return JsonResponse({"code": 1, "msg": "没有论文记录！", "data": [], "total": 0})

            # 可以加分页支持，例如传入 page 和 size 参数来分页
            page = request.query_params.get('page', 1)
            size = request.query_params.get('size', 10)
            start = (int(page) - 1) * int(size)
            end = start + int(size)

            # 分页查询
            paginated_theses = theses[start:end]

            serializer = ThesisModelSerializer(paginated_theses, many=True)
            return JsonResponse({
                "code": 0,
                "msg": "",
                "data": serializer.data,
                "total": theses.count()  # 返回总记录数
            })
        except ValueError:
            return JsonResponse({"code": 2, "msg": "传入的 id 不是有效的整数", "data": [], "total": 0})

    def post(self, request):
        serializer = ThesisDto(data=request.data)
        if serializer.is_valid():
            # 创建新的论文记录
            thesis = Thesis.objects.create(
                user_id=serializer.validated_data['user_id'],
                first_author=serializer.validated_data['first_author'],
                corresponding_author=serializer.validated_data['corresponding_author'],
                title=serializer.validated_data['title'],
                journal=serializer.validated_data['journal'],
                pub_year=serializer.validated_data['pub_year'],
                thesis_partition=serializer.validated_data['thesis_partition'],
                impact_factor=serializer.validated_data['impact_factor']
            )
            return Response({
                "code": 0,
                "msg": "",
                "data": {"thesis_id": thesis.id}
            })
        else:
            return Response({
                "code": 1,
                "msg": "参数错误",
                "errors": serializer.errors
            }, status=status.HTTP_400_BAD_REQUEST)


class ThesisPageListView(APIView):
    def post(self, request):
        serializer = ThesisPageQuery(data=request.data)
        if serializer.is_valid():
            page = serializer.validated_data['page']
            query = serializer.validated_data.get('query', None)

            # 实现分页逻辑
            page_size = page.get('size', 10)
            page_number = page.get('current', 1)
            start = (page_number - 1) * page_size
            end = start + page_size

            # 这里可以根据 query 来进行筛选
            theses = Thesis.objects.all()
            if query:
                theses = theses.filter(title__icontains=query)  # 例子：根据论文标题查询

            total = theses.count()
            records = theses[start:end]  # 实际分页

            return Response({
                "records": ThesisModelSerializer(records, many=True).data,
                "total": total,
                "size": page_size,
                "current": page_number,
                "orders": [],  # 订单排序可以根据需要添加
                "optimize_count_sql": False,
                "search_count": False,
                "optimize_join_of_count_sql": False,
                "count_id": "",
                "max_limit": 0,
                "pages": (total // page_size) + 1  # 计算总页数
            })
        else:
            return Response({
                "code": 1,
                "msg": "参数错误",
                "errors": serializer.errors
            }, status=status.HTTP_400_BAD_REQUEST)